package com.atguigu.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.pojo.TravelGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {
    @Autowired
    TravelGroupDao travelGroupDao;
    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
        //1.添加跟团游
        travelGroupDao.add(travelGroup);
        //2.添加跟团游和自由行的关系groupid itemid
        insert_group_item(travelGroup.getId(),travelItemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<TravelGroup> page = travelGroupDao.findPageByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }
    //回显 id 是跟团游的id
    @Override
    public TravelGroup getGroupById(Integer id) {
        return travelGroupDao.getGroupById(id);
    }

    //查询关联的自由行id  参数id是跟团游
    @Override
    public List<Integer> getItemById(Integer id) {
        return travelGroupDao.getItemById(id);
    }

    @Override
    public void edit(TravelGroup travelGroup, Integer[] travelItemIds) {
        //1.修改跟团游
        travelGroupDao.edit(travelGroup);
        //2.修改自由行和跟团游的关系
            //2.1删除原来的关系
        travelGroupDao.del_group_item(travelGroup.getId());
            //2.2添加新关系
        insert_group_item(travelGroup.getId(),travelItemIds);
    }

    @Override
    public void delete(Integer id) {
        //查询当前跟团游有没有被自由行关联
          Integer count = travelGroupDao.get_Item_Group(id);
        if (count > 0){
            throw new RuntimeException("bye");
        } else {
            //删除自由行
            travelGroupDao.delete(id);
        }
    }

    @Override
    public List<TravelGroup> findAll() {

        return travelGroupDao.findAll();
    }

    public void insert_group_item(Integer groupId,Integer[] travelItemIds){
        for (Integer travelItemid : travelItemIds){
            Map map = new HashMap();
            map.put("groupId",groupId);
            map.put("itemId",travelItemid);
            travelGroupDao.add_group_item(map);
        }
    }
}
